<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use DB;
use Curl\Curl;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Mockery\Exception;
use Latrell\Alipay;

class UserController extends Controller
{

    /*
    * 发送验证码
    */
    public  function requestSmsCode(Request $request)
    {

        $input = $request->only('username');
        $phone = $input['username'];
        $url = 'https://api.leancloud.cn/1.1/requestSmsCode';
        $content_type = "Content-Type: application/json";
        $x_id = "X-LC-Id:bwEfedhNXhEyAPgzYkbHnIJ9-gzGzoHsz";
        $x_key = "X-LC-Key: mWortLq8X7NBAeRkya3RjXbW";
        $array = [$content_type, $x_id, $x_key];
        $curl = new Curl();
        $curl->setOpt(CURLOPT_RETURNTRANSFER,1);
        $curl->setOpt(CURLOPT_POST,1);
        $curl->setOpt(CURLOPT_HTTPHEADER,$array);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER,false);
        $curl->setOpt(CURLOPT_SSL_VERIFYHOST,false);



        $curl->post($url,'{"mobilePhoneNumber": "'.$phone.'"}');

        return $curl->response;
    }
    /*
     * 验证验证码
     */
    public function verifySmsCode($SmsCode,$phone)
    {
        $url = 'https://api.leancloud.cn/1.1/verifySmsCode/' . $SmsCode . "?mobilePhoneNumber=" . $phone;
        $content_type = "Content-Type: application/json";
        $x_id = "X-LC-Id:bwEfedhNXhEyAPgzYkbHnIJ9-gzGzoHsz";
        $x_key = "X-LC-Key: mWortLq8X7NBAeRkya3RjXbW";
        $array = [$content_type, $x_id, $x_key];
        $curl = new Curl();
        $curl->setOpt(CURLOPT_RETURNTRANSFER,1);
        $curl->setOpt(CURLOPT_POST,1);
        $curl->setOpt(CURLOPT_HTTPHEADER,$array);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER,false);
        $curl->setOpt(CURLOPT_SSL_VERIFYHOST,false);
        $curl->post($url);


        return $curl->response;


    }
    /*
     * 用户登录
     */
    public function userLogin(Request $request)
    {
        try{
            $input = $request->only("username","password");
            $validator = Validator::make($input,[
                'username' => 'required|digits:11',
                'password' => 'required|max:16|min:4',
            ]);
            if ($validator->fails()) {
                return $validator->messages();
            }

            $rule['手机'] = $input['username'];
            $rule['密码'] = md5($input['password']);

            $result = DB::table("admin_user")->where($rule)->get();


            if(isset($result)&&!empty($result)){
                date_default_timezone_set("Asia/Shanghai");
                $time = date("Y-m-d h:i:sa");
                $token['token'] = md5($time);
                $token['最后上线日期'] = $time;
                $isLogin = DB::table("admin_user")->where($rule)->update($token);
                if($isLogin){
                    $result['token'] = $token['token'];
                    return response()->json(['msg'=>1,'data' => $result]);
                }else{
                    return response()->json(['msg'=>0,'data' => "登录失败，账号或密码错误"]);
                }
            }else{
                return response()->json(['msg'=>0,'data' => "登录失败，账号或密码错误"]);
            }
        }catch (Exception $e){
            $info =  $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            return response()->json(['msg'=>0,'data' => $info]);
        }

    }
    /*
     * 用户注册
     */
    public function userRegister(Request $request){
        try{
            $input = $request->only("username","verifyCode","password");
            $validator = Validator::make($input,[
                'username' => 'required|digits:11',
                'password' => 'required|max:16|min:4',
                'verifyCode' => 'required|digits:6',
            ]);

            if ($validator->fails()) {
                return $validator->messages();
            }
            $isIn = Db::table('admin_user')->where('手机',$input['username'])->get();
            if(isset($isIn)&&!empty($isIn)){
                return response()->json(['msg'=>0,'data' => '注册失败，该手机号已存在']);
            }

            $isCheckJson = $this->verifySmsCode($input['verifyCode'],$input['username']);
            $isCheck = json_decode($isCheckJson);
            if(empty(get_object_vars($isCheck))){
                $time = date("Y-m-d");
                $userData['手机'] = $input['username'];
                $userData['密码'] = md5($input['password']);
                $userData['注册日期'] = $time;
                $userData['最后上线日期'] = $time;
                $userData['过期时间'] = date('Y-m-d',strtotime('+10 day'));
                $userData['token'] = md5($time);

                $result = DB::table('admin_user')->insert($userData);
                if(isset($result)&&!empty($result)){
                    return response()->json(['msg'=>1,'data' => $userData]);
                }else{
                    return response()->json(['msg'=>0,'data' => '注册失败，请重试']);
                }

            }else{

                return $isCheckJson;
            }
        }catch (Exception $e){
            $info =  $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            return response()->json(['msg'=>0,'data' => $info]);
        }

    }

    /*
     * 忘记密码
     */
    public function forgetPwd(Request $request){
        $input = $request->only("username","verifyCode","password");
        $validator = Validator::make($input,[
            'username' => 'required|digits:11',
            'password' => 'required|max:16|min:4',
            'verifyCode' => 'required|digits:6',
        ]);

        if ($validator->fails()) {
            return $validator->messages();
        }
        $isIn = Db::table('admin_user')->where('手机',$input['username'])->get();


;        if(isset($isIn)&&empty($isIn)){
            return response()->json(['msg'=>0,'data' => '该手机号未注册']);
        }

        $isCheckJson = $this->verifySmsCode($input['verifyCode'],$input['username']);
        $isCheck = json_decode($isCheckJson);
        if(empty(get_object_vars($isCheck))){
            $time = date("Y-m-d");
            $updateData['密码'] = md5($input['password']);
            $updateData['最后上线日期'] = $time;
            $updateData['token'] = md5($time);

            $result = DB::table('admin_user')->where('手机',$input['username'])->update($updateData);
            if(isset($result)&&!empty($result)){

                $userData = Db::table('admin_user')->where('手机',$input['username'])->get();
                return response()->json(['msg'=>1,'data' => $userData]);
            }else{
                return response()->json(['msg'=>0,'data' => '修改密码，请重试']);
            }

        }else{

            return $isCheckJson;
        }
    }

    /*
     * 通过电话号码获取用户信息
     */
    public function getUserInfo(Request $request){
        $input = $request->only("username","token");
        $validator = Validator::make($input,[
            'username' => 'required|digits:11',
            'token' => 'required|size:32',
        ]);

        if ($validator->fails()) {
            return $validator->messages();
        }
        $rule['手机'] = $input['username'];
        $rule['token'] = $input['token'];

        $userData = DB::table('admin_user')->where($rule)->get();
        if(isset($userData)&&!empty($userData)){

            return response()->json(['msg'=>1,'data' => $userData]);
        }else{
            return response()->json(['msg'=>0,'data' => '获取失败']);
        }
    }
    /*
     * 用户个性设置入库
     */
    public function setUserSetting(Request $request){
        $input = $request->only('username','token','setting','game');
        $validator = Validator::make($input,[
            'username' => 'required|digits:11',
            'token' => 'required|size:32',
        ]);
        if ($validator->fails()) {
            return $validator->messages();
        }
        $rule['手机'] = $input['username'];
        $rule['token'] = $input['token'];
        $para= DB::table('admin_user')->where($rule)->select('参数')->first();
        $gameObj = (object)json_decode($para->参数);
        $gameObj->$input['game'] =json_decode($input['setting']);
        $setting['参数'] = json_encode($gameObj);


        $userData = DB::table('admin_user')->where($rule)->update($setting);
        if(isset($userData)&&!empty($userData)){

            return response()->json(['msg'=>1,'data' => '设置成功']);
        }else{
            return response()->json(['msg'=>0,'data' => '设置失败']);
        }

    }

    public function testPay()
    {
        $alipay = app('alipay.web');
        $alipay->setOutTradeNo('order_id');
        $alipay->setTotalFee('order_price');
        $alipay->setSubject('goods_name');
        $alipay->setBody('goods_description');

        $alipay->setQrPayMode('4'); //该设置为可选，添加该参数设置，支持二维码支付。

        // 跳转到支付页面。
        return redirect()->to($alipay->getPayLink());

    }
}
